package com.example.networklab;

import cn.dev33.satoken.SaManager;
import com.example.networklab.domain.po.Topology;
import com.example.networklab.domain.po.User;
import com.example.networklab.enums.UserRole;
import com.example.networklab.service.ITopologyService;
import com.example.networklab.service.IUserService;
import com.example.networklab.util.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.util.ArrayList;
import java.util.TimeZone;

@SpringBootApplication
@EnableScheduling
@Slf4j
@MapperScan("com.example.networklab.mapper")
public class NetworkLabApplication {

    public static void main(String[] args) {
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
        SpringApplication.run(NetworkLabApplication.class, args);
        System.out.println("启动成功，Sa-Token 配置如下：" + SaManager.getConfig());
    }

    @Bean
    public CommandLineRunner dataInit(IUserService userService, ITopologyService topologyService) {
        return new CommandLineRunner() {
            @Override
            public void run(String... args) {
                log.info("init data start.");
                if (!userService.exist("admin")) {
                    User user = new User();
                    user.setUsername("admin");
                    user.setPassword(PasswordUtil.encryptPassword("admin"));
                    user.setName("老师");
                    user.setRole(UserRole.TEACHER);
                    userService.save(user);
                    log.info("init admin user. [{}]", user);
                }
                if (topologyService.count() == 0) {
                    ArrayList<Topology> topologies = new ArrayList<>();
                    topologies.add(Topology.builder().id(1L).name("静态路由").graph("静态路由").topology("静态路由").build());
                    topologies.add(Topology.builder().id(2L).name("rip").graph("rip").topology("rip").build());
                    topologies.add(Topology.builder().id(3L).name("ospf").graph("ospf").topology("ospf").build());
                    topologyService.saveBatch(topologies);
                    log.info("init topology data. [{}]", topologies);
                }
                log.info("init data end.");
            }
        };
    }
}

